package repository

import (
	"gorm.io/gorm"
	"shyxy-model-agent/common/cache/lru"
	"shyxy-model-agent/core/model"
)

type selfBuildModelRepository struct {
	*BaseRepository
}

func NewSelfBuildModelRepository(db *gorm.DB) SelfBuildModelRepository {
	return &selfBuildModelRepository{
		BaseRepository: NewBaseRepository(db),
	}
}

func (sbmr *selfBuildModelRepository) Create(selfBuildModel *model.SelfBuildModel) error {
	return sbmr.GetDB().Create(selfBuildModel).Error
}
func (sbmr *selfBuildModelRepository) FindOneByModelInfoID(modelInfoID uint) (*model.SelfBuildModel, error) {
	var selfBuildModel model.SelfBuildModel
	err := sbmr.GetDB().Where("model_info_id = ?", modelInfoID).First(&selfBuildModel).Error
	return &selfBuildModel, err
}

func (sbmr *selfBuildModelRepository) FindOneByModelInfoIDWithModelInfo(modelInfoID uint) (*model.SelfBuildModel, error) {
	var selfBuildModel model.SelfBuildModel
	err := sbmr.GetDB().Preload("ModelInfo").Where("model_info_id = ?", modelInfoID).First(&selfBuildModel).Error
	return &selfBuildModel, err
}
func (sbmr *selfBuildModelRepository) DeleteByModelInfoID(modelInfoID uint) error {
	return sbmr.GetDB().Where("model_info_id = ?", modelInfoID).Delete(&model.SelfBuildModel{}).Error
}

type cachedSelfBuildModelRepository struct {
	*BaseCachedRepository
}

func (csbmr *cachedSelfBuildModelRepository) CachedRepository() {}

func NewCachedSelfBuildModelRepository(db *gorm.DB, cache *lru.LRU) SelfBuildModelRepository {
	return &cachedSelfBuildModelRepository{
		BaseCachedRepository: NewBaseCachedRepository(db, cache, "self_build_model"),
	}
}

func (csbmr *cachedSelfBuildModelRepository) Create(selfBuildModel *model.SelfBuildModel) error {
	return (&selfBuildModelRepository{BaseRepository: NewBaseRepository(csbmr.GetDB())}).Create(selfBuildModel)
}
func (csbmr *cachedSelfBuildModelRepository) FindOneByModelInfoID(modelInfoID uint) (*model.SelfBuildModel, error) {
	return (&selfBuildModelRepository{BaseRepository: NewBaseRepository(csbmr.GetDB())}).FindOneByModelInfoID(modelInfoID)
}

func (csbmr *cachedSelfBuildModelRepository) FindOneByModelInfoIDWithModelInfo(modelInfoID uint) (*model.SelfBuildModel, error) {
	return (&selfBuildModelRepository{BaseRepository: NewBaseRepository(csbmr.GetDB())}).FindOneByModelInfoIDWithModelInfo(modelInfoID)
}
func (csbmr *cachedSelfBuildModelRepository) DeleteByModelInfoID(modelInfoID uint) error {
	return (&selfBuildModelRepository{BaseRepository: NewBaseRepository(csbmr.GetDB())}).DeleteByModelInfoID(modelInfoID)
}

func NewSelfBuildModelRepositoryWithCache(db *gorm.DB, cache *lru.LRU) SelfBuildModelRepository {
	if cache != nil {
		return NewCachedSelfBuildModelRepository(db, cache)
	}
	return NewSelfBuildModelRepository(db)
}
